<template>
    <div>
        <!------用户管理查询按钮------>
        <div class="search">
            <el-input v-model="name" placeholder="请输入新闻标题" suffix-icon="el-icon-search" style="width: 220px;"
                      @keyup.enter.native="loadPost">
            </el-input>

            <el-button type="primary" style="margin-left: 10px;" @click="loadPost">查询</el-button>
            <el-button type="warning" @click="resetParam">重置</el-button>
            <el-button type="success" style="margin-left: 10px;" @click="add" v-if="users.userIdentity===1">新增
            </el-button>
        </div>

        <!------信息展示列表------>
        <el-table :data="tableData"
                  :header-cell-style="{color:'#c71111'}">
<!--            <el-table-column prop="id" label="ID" width="50">
            </el-table-column>-->
            <el-table-column type="index" label="序号" width="50">
            </el-table-column>

            <el-table-column prop="title" label="标题" width="200" show-overflow-tooltip>
            </el-table-column>

            <el-table-column prop="category" label="类型" width="90" sortable>
                <template slot-scope="scope">
                    <el-tag
                            :type="scope.row.category == 1 ? 'success' :'danger'"
                            disable-transitions>{{scope.row.category == 1 ? '新闻' :'公告'}}
                    </el-tag>
                </template>
            </el-table-column>

            <el-table-column prop="content" label="内容" width="300" show-overflow-tooltip>
            </el-table-column>


            <el-table-column prop="time" label="时间" sortable>
            </el-table-column>

            <el-table-column prop="operate" label="操作">
                <template slot-scope="scope">
                    <el-button size="small" type="success" @click="mod(scope.row)" v-if="users.userIdentity===1">编辑
                    </el-button>
                    <el-popconfirm
                            title="确定删除吗？"
                            @confirm="del(scope.row.id)"
                            style="margin-left: 10px;">
                        <el-button slot="reference" size="small" type="danger" v-if="users.userIdentity===1">删除
                        </el-button>
                    </el-popconfirm>
                    <el-button size="small" type="primary" style="margin-left: 10px;" @click="inspect(scope.row)">查看
                    </el-button>
                </template>
            </el-table-column>
        </el-table>


        <!------分页查询------>
        <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageNum"
                :page-sizes="[5, 9, 20, 30]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
        </el-pagination>


        <!------新增列表------>
        <el-dialog
                title="新闻公告管理"
                :visible.sync="centerDialogVisible"
                width="40%"
                center>

            <el-form ref="form" :rules="rules" :model="form" label-width="80px">

                <el-form-item label="标题" prop="title">
                    <el-col :span="20">
                        <el-input v-model="form.title"></el-input>
                    </el-col>
                </el-form-item>

                <el-form-item label="类型" prop="category">
                    <el-radio-group v-model="form.category">
                        <el-radio label="1">新闻</el-radio>
                        <el-radio label="2">公告</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="时间" prop="time">
                    <el-col :span="20">
                        <el-date-picker
                                v-model="form.time"
                                type="datetime"
                                placeholder="选择日期时间">
                        </el-date-picker>
                    </el-col>
                </el-form-item>

                <el-form-item label="内容" prop="content">
                    <el-col :span="20">
                        <el-input type="textarea" v-model="form.content"></el-input>
                    </el-col>
                </el-form-item>

                <el-form-item label="新闻图片" prop="image">
                    <el-col :span="20">
                        <el-upload
                                class="upload-demo"
                                :action="'http://'+ serverIp +':8090/sys-file/upload'"
                                :before-upload="handleBeforeUpload"
                                :on-success="handleSuccess"
                                list-type="picture-card"
                                :limit="1">
                            <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                    </el-col>
                </el-form-item>

            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="centerDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
            </span>
        </el-dialog>

        <!--查看抽屉-->
        <el-drawer :title="form.title" :visible.sync="drawer">
            <div class="drawTime">{{form.time}}</div>
            <div class="drawContent">{{ form.content }}</div>
            <div class="drawImage" v-if="form.imageUrl">
                <img :src="form.imageUrl" alt="图片" style="max-width: 380px; height: auto;">
            </div>
        </el-drawer>
    </div>
</template>

<script>

    import {serverIp} from "../../../public/config";

    export default {
        name: "MyNewsManage",
        data() {
            return {
                serverIp:serverIp,
                fileList: [],
                imgUrl: '',
                users: JSON.parse(sessionStorage.getItem('CurUser')),
                tableData: [],
                pageSize: 9,
                pageNum: 1,
                total: 0,
                name: '',

                centerDialogVisible: false,
                drawer: false,
                form: {
                    id: '',
                    title: '',
                    imageUrl: '',
                    category: '',
                    content: '',
                    time: '',
                    organization: '',
                },
                rules: {
                    title: [
                        {required: true, message: '请输入标题', trigger: 'blur'}
                    ],
                    category: [
                        {required: true, message: '请选择类型', trigger: 'blur'}
                    ],
                    time: [
                        {required: true, message: '请选择时间', trigger: 'blur'}
                    ],
                    content: [
                        {required: true, message: '请输入内容', trigger: 'blur'}
                    ],
                }

            };
        },
        methods: {
            inspect(row) {
                this.drawer = true;
                this.form.title = row.title;
                this.form.content = row.content;
                this.form.time = row.time;
                this.form.imageUrl = row.imageUrl;
            },
            handleBeforeUpload(file) {
                const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
                const isLt10M = file.size / 1024 / 1024 < 10;

                if (!isJPG) {
                    this.$message.error('上传图片只能是 JPG/PNG/GIF 格式!');
                }
                if (!isLt10M) {
                    this.$message.error('上传图片大小不能超过 10MB!');
                }

                return isJPG && isLt10M;
            },
            handleSuccess(res) {
                if (res) {
                    console.log(res)
                    this.form.imageUrl = res;
                    this.$message.success("上传成功")
                } else {
                    this.$message.error("上传失败");
                }

            },


            mounted() {
                // 获取当前用户信息
                const users = JSON.parse(sessionStorage.getItem('CurUser'))
                // 将当前用户的机构名赋值给 form 对象的 organization 属性
                this.form.organization = users.organization
            },

            resetForm() {
                this.$refs.form.resetFields();

            },

            del(id) {
                console.log(id);

                this.$axios.get('http://'+ serverIp +':8090/news/delete?id=' + id)
                    .then(res => res.data).then(res => {
                    console.log(res);
                    if (res.code == 200) {
                        this.$message({
                            message: '操作成功！',
                            type: 'success'
                        });
                        this.centerDialogVisible = false;
                        this.loadPost();
                    } else {
                        this.$message({
                            message: '操作失败！',
                            type: 'error'
                        });
                    }
                })
            },

            mod(row) {
                console.log(row);

                this.centerDialogVisible = true
                this.$nextTick(() => {
                    //赋值到表单
                    this.form.id = row.id;
                    this.form.title = row.title;
                    this.form.category = row.category + '';
                    this.form.content = row.content;
                    this.form.time = row.time;
                    this.form.organization = row.organization;
                    this.form.imageUrl=row.imageUrl;
                })
            },

            doMod() {
                this.$axios.post('http://'+ serverIp +':8090/news/update', this.form)
                    .then(res => res.data).then(res => {
                    console.log(res);
                    if (res.code == 200) {
                        this.$message({
                            message: '操作成功！',
                            type: 'success'
                        });
                        this.centerDialogVisible = false;
                        this.loadPost();
                        this.resetForm()
                    } else {
                        this.$message({
                            message: '操作失败！',
                            type: 'error'
                        });
                    }
                })
            },

            doSave() {
                this.$axios.post('http://'+ serverIp +':8090/news/save', this.form)
                    .then(res => res.data).then(res => {
                    console.log(res);
                    if (res.code == 200) {
                        this.$message({
                            message: '操作成功！',
                            type: 'success'
                        });
                        this.centerDialogVisible = false;
                        this.loadPost();
                        this.resetForm()
                    } else {
                        this.$message({
                            message: '操作失败！',
                            type: 'error'
                        });
                    }
                })
            },

            save() {
                this.$refs.form.validate((valid) => {
                        if (valid) {
                            if (this.form.id) {
                                this.doMod();
                            } else {
                                this.doSave();
                            }
                        } else {
                            console.log('error!!!');
                            return false;
                        }
                    }
                )
            },

            add() {
                this.centerDialogVisible = true;
                this.$nextTick(() => {
                    this.resetForm();
                    this.mounted()
                })
                this.$refs.upload.clearFiles();
            },

            resetParam() {
                this.name = '';
                this.userIdentity = '';
                this.loadPost()
            },

            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.pageNum = 1;
                this.pageSize = val;
                this.loadPost()
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.pageNum = val;
                this.loadPost()
            },

            loadGet() {
                this.$axios.get('http://'+ serverIp +':8090/news/list').then(res => res.data).then(res => {
                    console.log(res)
                })
            },

            loadPost() {
                this.$axios.post('http://'+ serverIp +':8090/news/page', {
                    pageSize: this.pageSize,
                    pageNum: this.pageNum,

                    param: {
                        name: this.name,
                        organization: this.users.organization,
                    }
                }).then(res => res.data).then(res => {
                    console.log(res);
                    if (res.code == 200) {
                        this.tableData = res.data
                        this.total = res.total
                    } else {
                        alert('获取数据失败')
                    }

                })
            }
        },

        beforeMount() {
            this.loadPost();
        }
    }
</script>

<style scoped>
    .drawImage {
        margin-top: 20px;
        text-align: center;
    }

    .drawTime {
        text-align: center;
        margin-bottom: 10px;
    }

    .drawContent {
        margin-left: 30px;
        margin-right: 30px;
    }

    .search {
        margin-bottom: 5px;
    }
</style>